#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2022-04-28 13:47
# @Author  : 徐昌龙
# @FileName: dict_server.py
"""
接收请求，逻辑处理，发送响应
"""
from socket import socket
from multiprocessing import Process
from dict_db import *


class Handle(Process):
    def __init__(self, conn):
        self.conn = conn
        self.name = ""
        self.db = Dict()
        super().__init__()

    def run(self):
        while True:
            request = self.conn.recv(1024).decode()
            temp = request.split("\t")
            print(temp)
            if not request or temp[0] == "E":
                break
            elif temp[0] == "R":
                self.do_register(temp[1], temp[2])
            elif temp[0] == "L":
                self.do_login(temp[1], temp[2])
            elif temp[0] == "Q":
                self.do_query(temp[1])
            elif temp[0] == "H":
                self.do_hist()
        self.db.close()
        self.conn.close()

    def do_register(self, name, passwd):
        if self.db.register(name, passwd):
            self.conn.send(b"T")
        else:
            self.conn.send(b"F")

    def do_login(self, name, passwd):
        if self.db.login(name, passwd):
            self.conn.send(b"T")
            self.name = name
        else:
            self.conn.send(b"F")

    def do_query(self, word):
        mean = self.db.query(word)
        if mean:
            res = f"T\t{mean}"
            self.conn.send(res.encode())
            self.db.insert_hist(self.name, word)
        else:
            self.conn.send(b"F")

    def do_hist(self):
        data = self.db.hist(self.name)
        if data:
            res = "T\t"
            for row in data:
                res += "%s##%s##%s##%s//" % row
            self.conn.send(res.encode())
        else:
            self.conn.send(b"F")


class DictServer:
    def __init__(self, host="", port=0):
        self.host = host
        self.port = port
        self.address = (host, port)
        self.sock = self.__create_sock()

    def __create_sock(self):
        sock = socket()
        sock.bind(self.address)
        return sock

    def serve_forever(self):
        self.sock.listen(5)
        print("Listen the port %d" % self.port)
        while True:
            conn, addr = self.sock.accept()
            print(f"Connect from {addr}")
            handle = Handle(conn)
            handle.start()


if __name__ == '__main__':
    dict_server = DictServer("0.0.0.0", 1314)
    dict_server.serve_forever()
